package com.zh.note.common.model;

import java.util.*;
import java.util.concurrent.*;

/**
 * 事件发布
 */
public class EventDelegate {
    private final Map<String, List<EventListener>> listeners = new HashMap<>();
    private final List<Event<?>> events = new ArrayList<>();
    public static final ExecutorService EXECUTOR = new ThreadPoolExecutor(10, 10, 60,
            TimeUnit.SECONDS, new LinkedBlockingQueue<>(1000), Executors.defaultThreadFactory(), new ThreadPoolExecutor.DiscardOldestPolicy());

    /**
     * 注册监听器
     */
    public void registerListener(String key, List<EventListener> listener) {
        if (!listeners.containsKey(key)) {
            List<EventListener> list = new ArrayList<>();
            listeners.put(key, list);
        } else {
            listeners.put(key, listener);
        }

    }

    /**
     * 事件发布
     *
     * @param key
     * @param event
     */
    public void publishEvent(String key, Event<?> event) {
        List<EventListener> eventListeners = listeners.get(key);
        if (eventListeners != null) {
            EXECUTOR.execute(new Task(key, event));
            EXECUTOR.shutdown();
        }

    }

    public class Task implements Runnable {
        private String key;
        private Event<?> event;

        public Task(String key, Event<?> event) {
            this.key = key;
            this.event = event;
        }

        @Override
        public void run() {
            List<EventListener> eventListeners = listeners.get(key);
            for (EventListener eventListener : eventListeners) {
                eventListener.onEvent(this.event);
            }
        }
    }
}
